//
//  HistoryListViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit

class HistoryListViewController: RViewController {

    @IBOutlet weak var chartBgView: UIView!
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var weekBtn: UIButton!
    @IBOutlet weak var monthBtn: UIButton!
    @IBOutlet weak var yearBtn: UIButton!
    
    /// 当前选中按钮
    var currentSelectBtn = SelectType.week
    // 按钮选中背景
    var selectImg = UIImageView()
    /// 当前数据源
    var dataArray = [[RModel]]()
    /// 当前数据源
    var allDataArray = [[RModel]]()
    /// tableViewCell每个数据对应的时间戳timeStamp
    var dataTimeStampArray = [String]()
    /// 时间段数组 [当前，"当前 - 间隔"， "当前 - 间隔" ... "2022-1-1"]
    var timeRangArray = [Int]()
    
    var device: VTDevice?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 按钮选中背景
        self.selectImg = UIImageView.init()
        self.selectImg.image = UIImage.init(named: "HistoryBtnBg")
        self.view.insertSubview(self.selectImg, at: 0)
        
        // 刷新
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name(HistoryShouldReload), object: nil)
        
        self.chartBgView.addSubview(collectionView)
    }
    
    @IBAction func weekBtnDidClicked(_ sender: UIButton) {
        self.currentSelectBtn = .week
        self.setBtnSelect(sender: self.weekBtn)
        self.setBtnDisClicked(sender: self.monthBtn)
        self.setBtnDisClicked(sender: self.yearBtn)
    }
    
    @IBAction func monthBtnDidClicked(_ sender: UIButton) {
        self.currentSelectBtn = .month
        self.setBtnSelect(sender: self.monthBtn)
        self.setBtnDisClicked(sender: self.weekBtn)
        self.setBtnDisClicked(sender: self.yearBtn)
    }
    
    @IBAction func yearBtnDidClicked(_ sender: Any) {
        self.currentSelectBtn = .year
        self.setBtnSelect(sender: self.yearBtn)
        self.setBtnDisClicked(sender: self.monthBtn)
        self.setBtnDisClicked(sender: self.weekBtn)
    }
    
    /// 按钮选中
    func setBtnSelect(sender: UIButton) {
        self.selectImg.frame = CGRect(x: sender.left, y: sender.top, width: self.weekBtn.width, height: 40)
        sender.layer.borderWidth = 0
        sender.setTitleColor(UIColor.white, for: .normal)
        sender.layer.cornerRadius = 0
        self.reloadData()
    }
    
    /// 按钮非选中
    func setBtnDisClicked(sender: UIButton) {
        sender.setBackgroundImage(nil, for: .normal)
        sender.layer.borderWidth = 1
        sender.layer.borderColor = hexColor("E8E8E8")?.cgColor
        sender.layer.cornerRadius = 16
        sender.setTitleColor(hexColor("999999"), for: .normal)
    }
    
    /// 切换按钮，刷新数据
    @objc func reloadData() {
        self.dataArray.removeAll()
        self.allDataArray.removeAll()
        self.timeRangArray.removeAll()
        
        if let history = RManager.manager.currentHistoryDevice {
            self.device = history
        }
        
        if let currentDevice = RManager.manager.currentDevice {
            self.device = currentDevice
        }
        
        guard let device = device else {
            self.tableView.reloadData()
            self.collectionView.contentOffset = CGPoint(x: 0, y: 0)
            self.collectionView.reloadData()
            return
        }
        
        var timeLimit = 60 * 60 * 24 // 天
        // 周
        if self.currentSelectBtn == .week {
            timeLimit = timeLimit * 7
        }
        // 月
        if self.currentSelectBtn == .month {
            timeLimit = timeLimit * 30
        }
        // 年
        if self.currentSelectBtn == .year {
            timeLimit = timeLimit * 365
        }
        // 从本地取数据
        // 当前时间戳
        let currentStamp = Int(Date().timeIntervalSince1970)
        // 开头时间戳
        let startStamp: Int = 1640966400
        
        var timeInterval = [Int]()
        self.addInterval(startStamp: startStamp, currentStamp: currentStamp, interval: timeLimit, timeInterval: &timeInterval)
        self.timeRangArray = timeInterval
        // 创建 timeInterval.count - 1 个空数组，便利本地数据，存储到对应的时间间隔里
        self.dataArray = [[RModel]](repeating: [RModel](), count: timeInterval.count - 1)
        
        // 本地数据
        if let timeList = CacheManager.manager.getValueForKey(HistoryData) as? [String] {
            for timeStamp in timeList {
                
                if let modelList = CacheManager.manager.getValueForKey(timeStamp) as? [RModel] {
                    
                    // 是否当前设备
                    if device.identifiers != modelList.first?.identifiers {
                        continue
                    }
                    
                    // 当前选中时间段数据源 取出来的时间戳，放到对应的时间段的index里
                    for (index, obj) in timeInterval.enumerated() {
                        if index > 0, Int(timeStamp)! > obj, Int(timeStamp)! < timeInterval[index - 1] {
                            self.dataArray[index - 1].append(contentsOf: modelList)
                            break
                        }
                    }
                    // 所有数据源
                    self.dataTimeStampArray.insert(timeStamp, at: 0)
                    self.allDataArray.insert(modelList, at: 0)
                }
            }
        }
        self.tableView.reloadData()
        self.collectionView.contentOffset = CGPoint(x: 0, y: 0)
        self.collectionView.reloadData()
    }
    
    /// 根据时间间隔分成n个数组  当前时间 -- (当前时间 - 间隔) -- (当前时间 - 间隔) -- 开始时间(2022-1-1)
    @discardableResult
    func addInterval(startStamp: Int, currentStamp: Int, interval: Int, timeInterval: inout [Int]) -> [Int] {
        let current = currentStamp
        if currentStamp > startStamp {
            timeInterval.append(current)
            addInterval(startStamp: startStamp, currentStamp: current - interval, interval: interval, timeInterval: &timeInterval)
        }else {
            timeInterval.append(startStamp)
        }
        return timeInterval
    }
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize.init(width: kScreenWidth, height: self.chartBgView.height)
        let collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: chartBgView.height), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(HistoryListCollectionCell.self, forCellWithReuseIdentifier: HistoryListCollectionCellId)
        return collectionView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.reloadData()
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewDidLayoutSubviews() {
        if self.selectImg.width == 0 {
            switch self.currentSelectBtn {
            case .week:
                self.weekBtnDidClicked(self.weekBtn)
            case .month:
                self.monthBtnDidClicked(self.monthBtn)
            case .year:
                self.yearBtnDidClicked(0)
            }
        }
    }
    
}

extension HistoryListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allDataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryListTableViewCell") as! HistoryListTableViewCell
        cell.selectionStyle = .none
        
        let modelList = allDataArray[indexPath.row]
        cell.modelList = modelList
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = getStoryBoardVC(identifier: "DetailViewController") as! DetailViewController
        vc.hidesBottomBarWhenPushed = true
        vc.timeStamp = self.dataTimeStampArray[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension HistoryListViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HistoryListCollectionCellId, for: indexPath) as! HistoryListCollectionCell
        
        cell.currentSelectBtn = self.currentSelectBtn
        cell.startTimeStamp = self.timeRangArray[indexPath.row]
        cell.endTimeStamp = self.timeRangArray[indexPath.row + 1]
        cell.loadChartViewData(historyData: self.dataArray[indexPath.row])
        
        return cell
    }
    
}
